<template>
    <div>
        <!-- 卡片视图区 -->
         <el-card class="main_card"> 
              <!-- 提示区域 -->
              <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
              <!-- 步骤条区域 -->
              <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="共享信息"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品介绍"></el-step>
                <el-step title="完成"></el-step>
              </el-steps>
              <!-- 侧边标签栏 -->
              <!-- form嵌套tabs -->
              <el-form :model="addForm" :rules="addFormrules" ref="addFormRef" label-width="100px" label-position="top">
               <el-tabs tab-position="left"  v-model="activeIndex" :before-leave="beforeTabLeave">

                <el-tab-pane label="基本信息" name="0">
                    <el-form-item label="商品名称" prop="name">
                       <el-input v-model="addForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="商品分类" >
                        <el-cascader v-model="newGoodCatId" :options="cateList" :props="cascaderProps" @change="handleChange"></el-cascader>
                    </el-form-item>
                </el-tab-pane>

                <el-tab-pane label="共享信息" name="1">
                    <el-form-item label="价格/时" >
                       <el-input v-model="addForm.moneyPerHour" type="number"></el-input>
                    </el-form-item>
                     <el-form-item label="位置" >
                       <el-input v-model="locationText"  @click.native="chooseLocation"></el-input>    
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="商品图片" name="2">
                    <!-- action表示图片要上传到的后台API地址 -->
                    <el-upload  :action="uploadURL" :on-preview="handlePreview" 
                    :on-remove="handleRemove" list-type="picture" :on-success="handleSuccess" name="uploadFile" :headers="header">
                        <button size="small" type="primary" class="uploadImg_btn">点击上传</button>
                    </el-upload>
                </el-tab-pane>
                <el-tab-pane label="商品介绍" name="3">
                    <!-- 富文本编辑器 -->
                    <quill-editor v-model="addForm.description"></quill-editor>
                    <button  class="addFinal_btn" @click="addNewGoods">添加商品</button>
                </el-tab-pane>
               </el-tabs>
              </el-form>
              
         </el-card>

         <!-- 图片预览 -->
         <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="50%" >
             <img :src="previewPath" alt="" class="previewImg">
         </el-dialog>

         <el-dialog :visible.sync="locationDialogVisible" destroy-on-close>
             <div id="locationmap"></div>
             <h1>{{locationText}}</h1>
        </el-dialog>

            
        
    </div>
</template>




<script>
export default {
    data(){
        return{
            longitude: "",
            latitude: "",
            activeIndex:'0',
            header:{merchant:window.sessionStorage.getItem("merchant")},
            locationDialogVisible:false,
            locationText:'',
            addForm:{
                url:'',
                name:'',
                catId:'',
                description:'',
                moneyPerHour:'',
                addressX:'',
                addressY:'',
                merchantId:1 
            },
            addFormrules:{
                name:[{required:true,message:"请输入商品名称",trigger:'blur'}]

            },
            checkIfPass:false,
            newGoodCatId:'',
            cateList:[],
            cascaderProps:{
                value:'catId',
                label:'catName',
                children:'cats',
                expandTrigger: 'hover',
                checkStrictly:true,
                emitPath:false
            },
            uploadURL:'http://119.23.40.43/rent/upload',
            previewPath:'',
            previewDialogVisible:false

        }
    },
    created(){
        this.getCateList();
    },
    methods:{
        //   获取商品分类数据
      async getCateList(){
          const{data:res}=await this.$http.get('rent/cat/findBypid/0');
          console.log(res);
          if(res.code!=200)
          return this.$message.error("获取商品分类失败!")
          this.cateList=res.data;
      },
      handleChange(){
        console.log(this.newGoodCatId)
        this.addForm.catId=this.newGoodCatId;
      },
      beforeTabLeave(activeName,oldActiveName){
          this.$refs.addFormRef.validate(valid=>
          {
              if(!valid)
              return this.$message.error("请填写完整的基本信息!");
              this.checkIfPass=true;
          })
          if(this.checkIfPass==false)
            return false;
      },
      chooseLocation()
      {
          this.locationDialogVisible=!this.locationDialogVisible;
          this.$nextTick(()=>{
               var that=this;
            var position = document.getElementById("locationmap");

            var center = new TMap.LatLng(30.526230995480322, 114.35812750362396);//设置中心点坐标
            //初始化地图
            var map = new TMap.Map("locationmap", {
                center: center
            });
            var markerLayer = new TMap.MultiMarker({
            id: 'marker-layer',
            map: map
        });
            
            //绑定点击事件
            map.on("click",function(evt){
                var lat = evt.latLng.getLat().toFixed(6);
                var lng = evt.latLng.getLng().toFixed(6);
                markerLayer.remove(0);
                markerLayer.add({
            	position: evt.latLng
                });
                that.addForm.addressX=lat;
                that.addForm.addressY=lng;
                that.getAddress(lat,lng);
            })
          })
      },
      getAddress(lat,lng)
      {
          var that=this;
            const KEY ="IJQBZ-XYJYJ-QZSFO-KDSBN-KX5KT-TKFEN"; //key 秘钥自己申请
	        let url = 'https://apis.map.qq.com/ws/geocoder/v1?&poi_options=address_format=short&get_poi=0';
	        let locationdata = lat+','+lng //纬度，经度
	        this.$jsonp(url,{
	          key:KEY,
	          callbackName: 'QQmap',
	          output:'jsonp',
	          location:locationdata
	        })
			.then(json => {
				let address = json.result.address;
	            console.log(json) //附近街道地址信息
                that.locationText=address;
					})
				.catch(err => {
						console.log(err)
				})
	  },
      handlePreview(file){
        this.previewPath=file.url;
        console.log(file.response);
        this.previewDialogVisible=true;
      },
      handleRemove(file){
          const filePath=file.response.data.tmp_path;
          const i=this.addForm.pics.findIndex(x=>x.pic==filePath);
          this.addForm.pics.splice(i,1);
          console.log(this.addForm);

      },
       handleSuccess(response){
          console.log(response)         
          this.addForm.url=response.data;        
      },
      addNewGoods(){
           this.$refs.addFormRef.validate(async valid=>{
              if(!valid)
              return this.$message.error("请填写必要的表单项!");             
             console.log(this.addForm);
             const {data:res}=await this.$http.post('rent/shareGoods/add',this.addForm);
             console.log(res);
             if(res.code!=200)
             return this.$message.error("添加商品失败!");
             this.$message.success("添加商品成功!");
             this.$router.push('/listShare');
          })
      },
    }

}
</script>

<style scoped lang="less">
#locationmap
{
    margin-top:10px;
}
.el-breadcrumb 
{
    margin-bottom:15px;
    font-size: 12px;
}

.el-steps
{
    margin:15px 0;
}
.el-checkbox
{
    margin:0 10px 0 0  im !important;
}
.previewImg
{
    width:100%;
}
.ql-editor
{
    min-height:300px;
}
/deep/.el-step__title.is-process
{
    color:#ff9a9e;
}
/deep/.el-step__head.is-process
{
    color:#ff9a9e;
    border-color: #ff9a9e;
}
.uploadImg_btn{
    border-radius:25px;
    margin-top:15px;
    margin-left:10px;
    height:40px;
    width:100px;
    font-weight:500;
    font-size:16px;  
    background-image: linear-gradient(-225deg, #E3FDF5 0%, #FFE6FA 100%);
    border:none;
    transition: 0.3s;
    cursor: pointer;
    color: #000;
    &:hover{
        transform: scale(1.1);
        
    }
}
.addFinal_btn{
    margin-top:15px;
    border-radius:25px;
    margin-left: 300px;
    height:40px;
    width:100px;
    font-weight:500;
    font-size:16px;  
    background-image: linear-gradient(to right, #f78ca0 0%, #f9748f 19%, #fd868c 60%, #fe9a8b 100%);
    border:none;
    transition: 0.3s;
    cursor: pointer;
    color: #000;
    &:hover{
        transform: scale(1.1);
        
    }
}
</style>